package com.zxy.bilibili.util;

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

/**
 * CommandUtils
 *
 * @author ZENG.XIAO.YAN
 * @version 1.0
 * @Date 2020-08-08
 */
@Slf4j
public class CommandUtils {

    public static void main(String[] args) throws Exception {
        ProcessBuilder processBuilder = new ProcessBuilder();
        processBuilder.command("cmd.exe", "/C","ping www.baidu.com");
        Process process = processBuilder.start();
        BufferedReader br =new BufferedReader(new InputStreamReader(process.getInputStream(), "GBK"));
        String line;
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }
    }

    /**
     * description: 执行cmd命令
     * @param commandList
     * @return void
     * @author ZENG.XIAO.YAN
     * @time 2020-08-08 15:10
     */
    public static void execCmd(List<String> commandList) {
        ProcessBuilder processBuilder = new ProcessBuilder(commandList);
        // 将由该对象的start()方法随后启动的子处理生成的任何错误输出将与标准输出合并，以便可以使用Process.getInputStream()方法读取。
        // 这使得更容易将错误消息与相应的输出相关联。
        processBuilder.redirectErrorStream(true);
        try {
            Process process = processBuilder.start();
            try (BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
                String line;
                log.debug("----执行cmd-----------------------start");
                while ((line = br.readLine()) != null) {
                    log.debug(line);
                }
                log.debug("----执行cmd-----------------------end");
            } catch (Exception e) {
                log.error("cmd通道流关闭异常", e);
            }
        } catch (IOException e) {
            log.error("打开cmd通道异常", e);
        }
    }
}
